﻿using System.Text;

namespace SUNRPA.CONTROLS.IMPL.util {
    public class QuotedPrintable{
        private const byte EQUALS = 61;
        private const byte CR = 13;
        private const byte LF = 10;
        private const byte SPACE = 32;
        private const byte TAB = 9;

        public static string Encode(string _ToEncode, Encoding encoding){
            StringBuilder Encoded = new StringBuilder();
            string hex = string.Empty;
            byte[] bytes = encoding.GetBytes(_ToEncode);
            int count = 0;

            for (int i = 0; i < bytes.Length; i++){
                if ((bytes[i] < 33 || bytes[i] > 126 || bytes[i] == EQUALS) && bytes[i] != CR && bytes[i] != LF && bytes[i] != SPACE){
                    if (bytes[i].ToString("X").Length < 2){
                        hex = "0" + bytes[i].ToString("X");
                        Encoded.Append("=" + hex);
                    }else{
                        hex = bytes[i].ToString("X");
                        Encoded.Append("=" + hex);
                    }
                }else{
                    if ((i + 1) < bytes.Length){
                        if ((bytes[i] == TAB && bytes[i + 1] == LF) || (bytes[i] == TAB && bytes[i + 1] == CR)){
                            Encoded.Append("=0" + bytes[i].ToString("X"));
                        }
                        else if ((bytes[i] == SPACE && bytes[i + 1] == LF) || (bytes[i] == SPACE && bytes[i + 1] == CR)){
                            Encoded.Append("=" + bytes[i].ToString("X"));
                        }
                        else{
                            Encoded.Append(System.Convert.ToChar(bytes[i]));
                        }
                    }
                    else{
                        Encoded.Append(System.Convert.ToChar(bytes[i]));
                    }
                }
                if (count == 75){
                    Encoded.Append("=\r\n"); 
                    count = 0;
                }
                count++;
            }
            return Encoded.ToString();
        }

        public static string Decode(string _ToDecode, Encoding encoding){
            try{
                _ToDecode = _ToDecode.Replace("=\r\n", "");
                char[] chars = _ToDecode.ToCharArray();
                byte[] bytes = new byte[chars.Length];
                int bytesCount = 0;
                for (int i = 0; i < chars.Length; i++){
                    if (chars[i] == '='){
                        bytes[bytesCount++] = System.Convert.ToByte(int.Parse(chars[i + 1].ToString() + chars[i + 2].ToString(), System.Globalization.NumberStyles.HexNumber));
                        i += 2;
                    }else{
                        bytes[bytesCount++] = System.Convert.ToByte(chars[i]);
                    }
                }
                return encoding.GetString(bytes, 0, bytesCount);
            }catch (Exception){
                return _ToDecode;
            }
        }
    }
}
